package org.etl.kfrwe.common;

import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;

public class DynamicScheduledTask implements SchedulingConfigurer {

    private static String cron = "0 */1 * * * *";
    private static String newCron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(doTask(), getTrigger());
    }

    private Trigger getTrigger() {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger trigger = new CronTrigger(getCron());
                return trigger.nextExecutionTime(triggerContext);
            }
        };
    }

    private String getCron() {
        String newCron = "0 */2 *  * * * ";
        if (StringUtils.isEmpty(newCron)) {
            throw new RuntimeException("The config cron expression is empty");
        }
        if (!newCron.equals(cron)) {
            System.out.println("Cron has been changed to:'" + newCron + "'. Old cron was:'"+ cron + "'");
            cron = newCron;
        }
        return cron;
    }

    private Runnable doTask() {
        return new Runnable() {
            @Override
            public void run() {
                System.out.println("执行了MyDynamicTask,时间为:" + new Date(System.currentTimeMillis()));
            }
        };
    }
}
